package cn.com.clearbus.handler;


import cn.com.clearbus.builder.AbstractBuilder;
import cn.com.clearbus.builder.FormatBuilder;
import cn.com.clearbus.builder.TextBuilder;
import cn.com.clearbus.enums.HtmlEnum;
import cn.com.clearbus.entity.weChat.msg.TextMsg;
import cn.com.clearbus.entity.weChat.msg.WeChatMsg;
import cn.com.clearbus.entity.weChat.node.EnterNode;
import cn.com.clearbus.entity.weChat.node.Node;
import cn.com.clearbus.entity.weChat.node.TitleNode;
import cn.com.clearbus.entity.weChat.node.UrlNode;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Value("${nameAddr}")
    String nameAddr;


    @Autowired
    @Lazy
    WxMpService wxMpService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());

        // 获取微信用户基本信息
        try {
            WxMpUser userWxInfo = weixinService.getUserService()
                .userInfo(wxMessage.getFromUser(), null);
            this.logger.info("当前存在用户关注，用户信息为:{}",userWxInfo);
            if (userWxInfo != null) {
                // TODO 可以添加关注用户到本地数据库
            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        }


        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {
            AbstractBuilder builder = new FormatBuilder(new TextBuilder(), genSubscribeTextMsg());
            return builder.build("感谢关注", wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
        throws Exception {
        //TODO
        return null;
    }

    private WeChatMsg<String> genSubscribeTextMsg(){
        List<Node<String>> list = new ArrayList<>();
        list.add(new TitleNode("感谢关注汉森运动"));
        list.add(new EnterNode(2));
        UrlNode urlNode = new UrlNode("进入主页", nameAddr + HtmlEnum.INDEX.getView());
        //UrlNode urlNode = new UrlNode("进入主页", nameAddr + HtmlEnum.INDEX.getView(),wxMpService.getWxMpConfigStorage().getAppId());
        urlNode.buildModelView(false);
        list.add(urlNode);
        return new TextMsg(list);
    }



}
